$(document).ready(function(){
   // Edit event
   $(document).on('click','#editEvent',function(){
      var totalfeedbacks = $(this).data('totalfeedbacks');
      //如果该轮的反馈已存在,则提示是否安排复试
      if(totalfeedbacks > 0) {
         showConfirmDialog("<div class=\"ciw_words\" ><i></i> 修改安排面试将会清空此轮已有的面试反馈，确认吗？<br/>" +
               "不想清空？您也可以 <a id='next_round_interview' style='cursor:pointer;'>安排复试</a></div>", function() {
            var data = {};
            var eventid = $('#editEvent').data('eventid');
            data.eventid = eventid;
            data.target = $('#editEvent');
            data.resultid = $('#editEvent').data('resultid');
            data.type = 0;
            data.validemail = $('#editEvent').data('validemail');
            editInterview(data);
         });
         return;
      }
      var data = {};
      var eventid = $(this).data('eventid');
      data.eventid = eventid;
      data.target = $(this);
      data.resultid = $(this).data('resultid');
      data.type = 0;
      data.validemail = $('#editEvent').data('validemail');
      editInterview(data);
   });
   
   //dialog中安排复试
   $(document).on('click','#next_round_interview',function(){
      jQuery("#dialogConfirm").modal('hide');
      $("#dropdownmenu").children("a:eq(2)").trigger("click");
   });
   
   //template中安排复试按钮
   $(document).on('click','#add_next_round_interview',function(){
      jQuery("#dialogConfirm").modal('hide');
      $("#dropdownmenu").children("a:eq(2)").trigger("click");
   });

   var editInterview = function(data){
      var target = data.target;
      var id = data.eventid;
      var type = data.type;
      var resultid = data.resultid; 
      var interview_form_type = $('input[name=interview_form_type]').val();
      var validemail = data.validemail;
      $.ajax({
         type: "POST",
         url: OC.filePath('calendar', 'ajax/event', 'edit.form.php'),
         data: {id: id,resultid: resultid,type:type,validemail:validemail},
         dataType: 'html',
         beforeSend: function(xhr, settings) {
            showLoading(target, settings, null, {button: true});
         },
         success: function(result){
            $("#preview_holder").hide();
            $("#modal_holder").html(result);
            $('label.checkbox.gray').tooltip();
            setTimeout(function () {
               if(!$('#modal_holder #sendemail').is(':checked')) {
                  if(!$('#modal_holder #sendsms').is(':checked') && $('#modal_holder #sendsms').attr("disabled") != "disabled") {
                     showMessagePanel('简历缺少Email信息，请设置发送短信', $("#modal_holder #sendsms").parent("label"), true, {placement:'right', timeout:3000});
                  }
               }
            }, 500);

            if($.isFunction($.fn.placeholder)) {
               $("input, textarea", "#modal_holder").placeholder();
            }

            // Init event form validate
            $("#modal_holder #event_form").validate({
               rules: {
                  contact_phone: {required:true,phone: true},
                  address: {required: true},
                  contact: {notalldigits:true}
               },
               messages: {
                  contact_phone: {
                     required: "请输入联系电话",
                     phone: "请输入正确的联系电话"
                  },
                  address: {
                     required: "请输入面试地点"
                  },
                  contact: {
                     notalldigits:"联系人不能为纯数字"
                  }
               },
               success:function(label){
                  var prev = $("#modal_holder #errorbox").data("element");
                  if ( label.attr("for") == prev && (prev == "contact_phone" || prev == "address" || prev == "contact") ) {
                     $("#modal_holder #errorbox").data("element", "").html("").hide();
                  }
               },
               errorPlacement:function(error,element) {
                  var validator = $("#modal_holder #event_form").data("validator");
                  if ( element.attr("name") == "during[]" ) {
                     error.insertAfter("#event_form #addinterviewer");
                  } else if ( element.attr("name") == "contact_phone" || element.attr("name") == "address" || element.attr("name") == "contact" ) {
                     var prev = $("#modal_holder #errorbox").data("element");
                     if(prev) {
                        if($.grep(validator.errorList, function(error, i) {      
                           if($(error.element).attr("name") == prev) 
                              return true;
                           return false;
                        }).length > 0)
                           return;
                     }
                     if(error.text()) {
                        $("#modal_holder #errorbox").data("element", element.attr("name")).jobUtil('showError', error.text());
                     }
                  }
                  else 
                     error.insertAfter(element);
               },
               submitHandler: function(form) {
                  if($("#modal_holder #editEvent-submit").hasClass("ppp_graybtn")) {
                     return false;
                  }
                  $("#modal_holder #event_form").ajaxSubmit({
                     type: 'post',
                     dataType: "json",
                     beforeSubmit: function(data, form, options) {
                        if (!showLoading("#modal_holder #editEvent-submit", options, null, {button:true}))
                           return false;
                        $("#modal_holder #errorbox").hide();
                     },
                     success: function(data) {
                        try {
                           var retmsg = data;
                           if (retmsg.error) {
                              $("#modal_holder #errorbox").jobUtil('showError', retmsg.error);
                           }
                           else if(retmsg.success) {
                              $('#modal_holder').modal('hide');
                              if (type == 1) {
                                 $('#searchinterview_dialog').modal('hide');
                                 $('#getresult_dialog').modal();
                                 $('#getresult_dialog').on('hidden',function(){
                                    window.location.reload();
                                 });
                              } else {
                                 var msg = "";
                                 if((retmsg.success.jobseeker_email_stat == 1 && retmsg.success.interviewer_email_stat ==1) || interview_form_type == 1){
                                    msg = "已发送面试通知给面试官和应聘者，";
                                 } else if(retmsg.success.interviewer_email_stat == 1 && !retmsg.success.jobseeker_email_stat){
                                    msg = "已发送面试通知给面试官，";
                                 } else if(!retmsg.success.interviewer_email_stat && retmsg.success.jobseeker_email_stat ==1){
                                    msg = "已发送面试通知给应聘者，";
                                 }
                                 if(msg != ""){
                                    $("#notify_showdialog .modal-body").html(msg + $("#notify_showdialog .modal-body").html());
                                    //email_stat 1:has sent email 0:has not sent email,interview_form_type 1: old interview had been canceled and reset new interview 
                                    var scrolltop = $(window).scrollTop();
                                    $("#notify_showdialog").css({top:scrolltop+100}).modal();
                                    $('#notify_showdialog').on('hidden',function(){
                                       window.location.reload();
                                 });
                                 }
                                 
                              }
                           }
                        } catch(e) {
                           return false;
                        }
                     }
                  });
               }
            });
            var scrolltop = $(window).scrollTop();
            $("#modal_holder").css({top:scrolltop+75}).modal('show');
          //edit interview attachment  
            jQuery('#uploadcalendarform').not('.file_upload').fileUploadUIX({
               allowOfficeTypes: true,
               keepList: true,
               autoUpload: true,
               maxFileSize: 4*1024*1024,
               onError:function(response){
                  $("#uploadcalendartable tr:last").remove();
                  $(".errors").show().html(' <div class="error">' + response +'</div>');;
                  $(".errors").fadeOut(3000);
                  return false;
               },
               onCompleteAll: function(list) {
                  jQuery.each(list, function(i, o) {
                     var handler = o.slice(-1)[0];
                     if(handler.response.error) {
                        $(".errors").show().html(' <div class="error">' + handler.response.error +'</div>');
                        $(".errors").fadeOut(3000);
                     }else{
                        $("#fileshowarea").show().html("<span class="+handler.response.attachid+" fileshoweach <em>"+handler.response.name+"</em> <a href='javascript:;' id='del_name' data = {'attachid':'"+handler.response.attachid+"','attachname':'"+handler.response.name+"'}>取消</a></br></span>");
                        $("#attachment").val(handler.response.attachid);
                        $(".errors").show().html(' <div class="success">成功上传</div>');
                        if(!$('#calendar_att_div .inviteselectmenubox').hasClass("dropdown")){
                           $('#calendar_att_div .inviteselectmenubox').addClass("dropdown");
                           $('#calendar_att_div .inviteselectmenubox .dropdown-toggle').dropdown();
                        }
                        $(".history_list").append("<a href='javascript:;' class='this"+handler.response.attachid+"'> <span  id='choosehistory' data={'attachname':'"+handler.response.name+"','attachid':'"+handler.response.attachid+"'} style='display:inline;'>"+handler.response.name+"</span><i data={'attachid':'"+handler.response.attachid+"','attachname':'"+handler.response.name+"'} id='history_atachment' class='delete'></i></a>");
                        $(".errors").fadeOut(3000);
                        $("#uploadcalendartable tr:last").remove();
                     }    
                  });
               }
           });
         }
      });
   };

   // Datepicker js
   $(document).on('focus','.startdate',function(){
      $(this).datepicker({
         dateFormat: 'yy-mm-dd',
         changeYear: true,
         changeMonth: true,
         numberOfMonths: 1,
         minDate: new Date(),
         onClose: function(dateText) {
            if(dateText != $(this).attr("title"))
               $(this).removeClass("blur");
            else
               $(this).blur();
         }
      });
   });

   var checkTime = function checkTime(timeStr) {
      var parts = timeStr.split(':');
      if (parts.length < 1) {
         //exst h & i 
         return false;
      }
      for (i = 0; i < parts.length; i++) {
         //whether a number
         if(isNaN(parts[i])){
            return false;
         }
      }
      if (parts[0] < 0 || parts[0] > 23 || parts[1] < 0 || parts[1] > 59) {
         return false;
      }

      return true;
   }; 
  
   var timeToNumber = function (timeStr){
      var parts = timeStr.split(":");
      if(parts.length <= 1)
         return parts.shift(); 

      return parseInt(parts[0]*60) + parseInt(parts[1]); 
   };
   
   var validateOfferTime = function(ftime,stime,etime){    
      $("#errorbox").hide();

      // when a time is not null, it should be in valid format 
      if((etime && !checkTime(etime)) || 
         (ftime && !checkTime(ftime)) ||
         (stime && !checkTime(stime))) {
         $("#errorbox").jobUtil('showError', '时间格式有误！');
         return false;
      }
     
      if(stime && etime && timeToNumber(etime) <= timeToNumber(stime)){
         $("#errorbox").jobUtil('showError', '面试官的结束时间必须大于开始时间！');
         return false;
      }

      if(ftime.length >0 && 
         (stime && timeToNumber(stime) < timeToNumber(ftime)) || 
         (etime && timeToNumber(etime) <= timeToNumber(ftime))) {
         $("#errorbox").jobUtil('showError', '面试官的开始时间不能小于总开始时间！');
         return false;
      }

   }
   //onchage js, validate starttime & endtiem  & endtiem >starttiem
   $(document).on('change focus','.eventtime',function(){
      var etime = null, stime = null;
      //first get fromtime to check and reject any time is smaller than fromtime 
      var ftime = $('#fromtime').val(); 

      if($(this).attr('name') == 'endtime[]'){
         etime = $(this).val();
         stime = $(this).siblings("input[name='starttime[]']").val();
      }else if($(this).attr('name') == 'starttime[]'){
         stime = $(this).val();
         etime = $(this).siblings("input[name='endtime[]']").val();
      }else if($(this).attr('name') == 'fromtime'){
         ftime = $(this).val();
   	}
      if (ftime && stime && etime) {
         validateOfferTime(ftime,stime,etime);
      }
   })
   
   $(document).on('change focus','#fromtime',function(){
      var etime = null;
      var ftime = $('#fromtime').val();
      etime = $('#interviewer_list .control-group').first().find('.eventtime').eq(1).val();
      if(etime && checkTime(etime)){
         if(ftime&&etime) {
            validateOfferTime(ftime,ftime,etime);
         }
      }
   })
   
   // Timepicker js
   $(document).on('focus','#fromtime,.eventtime',function(){
      if($(this).data('timepicker-settings') && $(this).val().length > 0)
         return true;

      // find out if there are previous endtime, if found, set it as default new start time  
      if($(this).hasClass('starttime') && $(this).val().length <= 0) {
         var prev = $(this).closest(".control-group").prevAll('.control-group').first();
         if(prev.length > 0) {
            var pTime = prev.find("input").eq(2).val();
            if(pTime.length > 0) 
               $(this).val(pTime);
         }
      }

      // the end time should have time based on start time 
      if($(this).hasClass('endtime') && ($(this).val().length <= 0)) {
         $(this).val($(this).prevAll('.starttime').first().val()); 
      }

      $(this).timepicker({
         timeFormat: 'H:i',
         step: '15',
         minTime: '07:00',
         maxTime: '21:00'
      });
   });
   
   //equal this endtime to the next starttime 
   $(document).on('change','.endtime,#fromtime',function(){
      var target = $(this);
      if(!target.hasClass('endtime')){
         var fromtime = target.val();
         $('#interviewer_list .control-group').first().find('.eventtime').eq(0).val(fromtime);
      }
   })
   
   function getpos_upload() {
      if($('#event_form').length>0){
         var uppos = $('#calendar_att_div').position().top+40;
         $('#uploadcalendarform.uploadform').css('top',uppos+'px');
      }   
   }

   // Add tpl js
   $(document).on('click','#notify_form #addtpl', function() {
      var target = $(this);
      var open = target.data('open');
      if ( open == 1 ) {
         $('#purposlistbox').hide();
         $('#purposlistbox #tpl_error').html('');
         target.data('open', 0);
         getpos_upload();
      } else {
         $('#purposlistbox').show();
         $('#purposlistbox #tpl_error').html('');
         target.data('open', 1);
         getpos_upload();
      }
      return false;
   });

   // Save tpl js
   $(document).on('click','#notify_form #savetpl', function() {
      var target = $(this);
      var data = {};
      var tplname=$("#notify_form input[name=tplname]").val();
      var tpl = $("#notify_form #notify_text").val();     
      var tpl_type = $("#notify_form").data("tpltype");

      if(tpl_type == 'notify'){
         var address = $("#notify_form #address").val();
         var contact_phone = $("#notify_form #contact_phone").val();
         var contact = $("#notify_form #contact").val();
      }
      $('#notify_form #tpl_error').html('').hide();
      if ( tplname.length <= 0) {
         $('#notify_form #tpl_error').html('请填写模板名称！').show();
         getpos_upload();
         return false;
      }
      if (tpl_type =='notify' && address.length <= 0) {
         $('#notify_form #tpl_error').html('请输入面试地点！').show();
         getpos_upload();
         return false;
      }
      if (tpl_type =='notify' && contact_phone.length <= 0) {
         $('#notify_form #tpl_error').html('请输入联系电话！').show();
         getpos_upload();
         return false;
      }

      if(tpl_type == 'offer' && tpl.length <=0){
         $('#notify_form #tpl_error').html('请填写补充，模板内容不能为空！').show();
         getpos_upload();
         return false;
      }
      if(tpl_type == 'notify'){
         data = {tplname: tplname, address: address, contact_phone: contact_phone, contact: contact, tpl: tpl, tpl_type: tpl_type};
      }else{
         data = {tplname: tplname, tpl: tpl, tpl_type: tpl_type};
      }
      
      $.ajax({
         type: "POST",
         url: OC.filePath('calendar', 'ajax/tpl', 'new.notify.php'),
         data: data,
         dataType: 'json',
         beforeSend: function(xhr, settings) {
            showLoading(target, settings, null, {button: true});
         },
         success: function(data){
            try {
               var retmsg = data;
               if (retmsg.error) {
                  $("#notify_form #tpl_error").jobUtil('showError', retmsg.error);
                  getpos_upload();
               }
               else if(retmsg.success) {
                  var retdata = retmsg.success;
                  target.closest(".purposlistbox").prev(".mod_action").find(".inviteselectmenubox").addClass('dropdown');
                  $('#notify_form #choose_tpl').attr('data-toggle','dropdown');
                  $('#notify_form #tpl_list').append('<a id="'+retdata.notify_id+'" href="javascript:;"><span class="apply" style="display:inline;">'+tplname+'</span><i class="delete"></i></a>');
                  $('#notify_form #purposlistbox').hide();
                  $('#notify_form #addtpl').data('open', 0);
                  getpos_upload();
               }
            } catch(e) { 
               return false;
            }
         }
      })
   });

   // Delete tpl js
   $(document).on('click','#notify_form #tpl_list .delete', function() {
      var target = $(this).parent();
      var del_id = target.attr('id');
      var tpl_type = $("#notify_form").attr("data-tpltype");
      $.ajax({
         type: "POST",
         url: OC.filePath('calendar', 'ajax/tpl', 'del.notify.php'),
         data: {del_id: del_id,tpl_type: tpl_type},
         dataType: 'json',
         beforeSend: function(xhr, settings) {
            showLoading(target, settings, null, {button: true});
         },
         success: function(data){
            try {
               var retmsg = data;
               if (retmsg.error) {
                  showMessagePanel(retmsg.error, target, true, {placement:'left'});
               }
               else if(retmsg.success) {
                  $('#notify_form #tpl_list #'+del_id).remove();
                  if( $('#notify_form #tpl_list').children().length==0 ) {
                     $('#notify_form .inviteselectmenubox').removeClass('dropdown open');
                     $('#notify_form #invs_one').removeClass('dropdown open');
                     $('#notify_form #choose_tpl').attr('data-toggle','');
                  }
               }
            } catch(e) {
               return false;
            }
         }
      });
      return false;
   });

   // Apply tpl js
   $(document).on('click','#notify_form #tpl_list .apply', function() {
      var target = $(this).parent();
      var apply_id = target.attr('id');
      var tpl_type = $("#notify_form").attr("data-tpltype");
      $.ajax({
         type: "GET",
         url: OC.filePath('calendar', 'ajax/tpl', 'get.notify.php'),
         data: {apply_id: apply_id,tpl_type: tpl_type},
         dataType: 'json',
         beforeSend: function(xhr, settings) {
            showLoading(target, settings, null, {button: true});
         },
         success: function(data){
            try {
               var retmsg = data;
               if (retmsg.error) {
                  showMessagePanel(retmsg.error, target, true, {placement:'left'});
               }
               else if(retmsg.success) {
                  var retdata = retmsg.success;
                  if ( !retdata.notify_tpl ) {
                     showMessagePanel('网络异常，请刷新重试！', target, true, {placement:'left'});
                  } else {
                     if(tpl_type == 'notify'){
                        $('#notify_form #notify_text').val(retdata.notify_tpl.tpl_text);
                        $('#notify_form #contact').val(retdata.notify_tpl.contact);
                        if(typeof retdata.notify_tpl.address != "undefined") {
                           $('#notify_form #address').val(retdata.notify_tpl.address);
                        }
                        if(typeof retdata.notify_tpl.contact_phone != "undefined") {
                           $('#notify_form #contact_phone').val(retdata.notify_tpl.contact_phone);
                        }
                        $("#modal_holder #event_form #address").removeClass("error");
                        $("#modal_holder #event_form #contact_phone").removeClass("error");
                        $("#modal_holder #event_form #contact").removeClass("error");
                        $("#modal_holder #event_form #tpl_error").html("");
                        $("#modal_holder #event_form #errorbox").html("");
                     }else{
                        $('#notify_form #notify_text').val(retdata.notify_tpl);
                     }
                  }
               }
            } catch(e) {
               return false;
            }
         }
      });
      return false;
   });

   $(document).on('click','#notify_form #tpl_list a', function() {
      $(this).find('.apply').trigger('click');
   });

   // Add interviewer js
   $(document).on('click','#event_form #addinterviewer', function() {
      var count = $('#event_form #interviewer_list').attr('count');
      var new_id = parseInt(count)+1;
      $('#interviewer_list').append('<div class="control-group"><label class="control-label" for="">面试官'+new_id+'：</label><div class="controls"><input type="text" name="interviewer[]" value="" placeholder="面试官邮箱地址" class="iptsolong">&nbsp;<input type="text" class="iptsomin eventtime starttime" value="" name="starttime[]"> <span>至</span> <input type="text" class="iptsomin eventtime endtime" value = "" name="endtime[]"/>');
      
      // Update total interviewer count
      $('#event_form #interviewer_list').attr('count', new_id);
      if($.isFunction($.fn.placeholder)) {
         $("input, textarea", "#event_modal").placeholder();
      }
      return false;
   });

   /*Send offer js */
   //Sendoffer input dialog
   $(document).on('click','#sendoffer',function(){
      var target = $(this);
      $.metadata.setType('attr', 'data');
      var data = $(this).metadata();
      var eventid = data.eventid;
      var objectid = data.objectid;
      var jobseekid = data.jobseekid;
      var jobid = data.jobid;
      var validemail = data.validemail;
      $.ajax({
         type: "GET",
         url: OC.filePath('calendar', 'ajax', 'sendoffer.php'),
         data: {eventid: eventid,objectid: objectid,jobseekid: jobseekid,jobid: jobid,validemail: validemail},
         dataType: 'html',
         cache: false,
         success: function(result){
            var scrolltop = $(window).scrollTop();
            $("#sendofferdialog").html(result).css({top:scrolltop+75}).modal();
            $('label.checkbox.gray').tooltip();
            setTimeout(function () {
               if(!$('#sendofferdialog #sendemail').is(':checked')) {
                  if(!$('#sendofferdialog #sendsms').is(':checked') && $('#sendofferdialog #sendsms').attr("disabled") != "disabled") {
                     showMessagePanel('简历缺少Email信息，请设置发送短信', $("#sendofferdialog #sendsms").parent("label"), true, {placement:'right', timeout:3000});
                  }
               }
            }, 500);
            if($.isFunction($.fn.placeholder)){
               $("input, textarea", "#sendofferdialog").placeholder();
            }
            if($('#uploadofferForm').length>0) {
               $('#uploadofferForm').not('.file_upload').fileUploadUIX({
                  allowOfficeTypes: true,
                  keepList: true,
                  autoUpload: true,
                  maxFileSize: 4*1024*1024,
                  onError:function(response){
                     $("#uploadoffererror").html("").html('<span class="failture">'+response+'</span>');
                     $("#uploadoffererror .failture").fadeOut(2000);
                     $("#uploadTable tr:last").remove();
                     return false;
                  },
                  onCompleteAll: function(list) {
                     var errors = []; 
                     var success = []; 
                     jQuery.each(list, function(i, o) {
                        var handler = o.slice(-1)[0]; 
                        if(handler.response.error && handler.response.error.length > 0) {
                           errors[errors.length] = handler.response.name;
                        }
                        else{
                           var attachid = handler.response.attachid;
                           var filename = handler.response.name;
                           $("#uploadoffererror").html("").html('<div class="success">成功上传</div>');
                           $("#uploadoffererror .success").fadeOut(2000);
                           $("#filename").val(filename);
                           $('#uploadTable').find('tr.file_upload_error.keeprow').fadeOut(2000, function(){
                              $(this).remove();
                              $('#attachment #filename').remove();
                              $('#notify_form #attachment').prepend('<input type="text" value="'+filename+'" attachmentid = "'+attachid+'" placeholder="" name="" id="filename" readonly="readonly" style="width:258px;">');
                              $('#attachment .inviteselectmenubox').addClass('dropdown');
                              $('#attachment #choose_tpl').attr('data-toggle','dropdown');
                              $('#attachment #attachment_list').append('<a class="apply" id="'+attachid+'" href="javascript:;"><span style="display:inline;">'+filename+'</span><i class="delete"></i></a>');
                           });
                           $("#uploadofferForm #uploadform").addClass("upload_offer_position");
                           $("#uploadTable tr:last").remove();
                        }
                     })
                     
                     if(errors.length > 0 || success.length <= 0)
                        return;
                  }
                  
               });
               return false;
            }
         }
      });
   });

   //Backedit js
   $(document).on('click','#backedit',function(){
      $("#interviewsuccess").modal('hide');
      var scrolltop = $(window).scrollTop();
      $("#sendofferdialog").css({top:scrolltop+75}).modal('show');
   });

   //Preview offer dialog
   $(document).on('click','#previewoffertpl', function(){
      if($(this).hasClass("ppp_graybtn")) {
         return false;
      }
      var icomp_name = $("#sendofferdialog #icomp_name").val();
      var jobseekername = $("#sendofferdialog #jobseekername").val();
      var jobseekerid = $("#sendofferdialog input[name=jobseekerid]").val();
      var department = $("#sendofferdialog input[name=department]").val();
      var jobid = $("#sendofferdialog #jobid").val();
      var jobtitle = $("#sendofferdialog #jobtitle").val();
      var textval = $("#sendofferdialog #notify_text").val();
      var fromtime = $("#sendofferdialog #fromtime").val();
      var from = $("#sendofferdialog #sendfrom").val();
      var entryenddate = $("#sendofferdialog #entryend").val();
      var salary = $("#sendofferdialog input[name=salary]").val();
      var entrysalary = $("#sendofferdialog input[name=entrysalary]").val();
      var objectid = $("#sendofferdialog #objectid").val();
      var filename = $("#sendofferdialog #filename").val();
      var attachmentid = $("#sendofferdialog #filename").attr('attachmentid');
      var copywith = $.trim($("#sendofferdialog #copywith").val().replace(/；|，|;/g, ','));
      var eventtype = $("#sendofferdialog #previewoffertpl").attr('eventtype');
      var eventid = $("#sendofferdialog #eventid").val();
      var type = $("#sendofferdialog #marker").val();
      var calendar = $("#sendofferdialog #calendar").val();
      var sendsms = $("#sendofferdialog #sendsms").val();
      if(from == ''){
         $('#sendofferdialog #saveerror').html('入职日期不能为空！').fadeIn().fadeOut(5000);
         return false
      }
      if(!/^\d{4}?[\.\/-]\d{1,2}([\.\/-]\d{1,2})$/.test(from)) {
         $('#sendofferdialog #saveerror').html('入职日期格式不正确！').fadeIn().fadeOut(5000);
         return false
      }
      if(fromtime == ''){
         $('#sendofferdialog #saveerror').html('入职时间不能为空！').fadeIn().fadeOut(5000);
         return false
      }
      if(!/^([01]\d|2[0-3])(:[0-5]\d){0,2}$/i.test(fromtime)) {
         $('#sendofferdialog #saveerror').html('入职时间式不正确！').fadeIn().fadeOut(5000);
         return false
      }
      if(salary != '' && (!/^\d+$/.test(salary) || salary <= 0)){
         $('#sendofferdialog #saveerror').html('转正月薪必须为正整数！').fadeIn().fadeOut(5000);
         return false;
      }
      if(entrysalary != '' && (!/^\d+$/.test(entrysalary) || entrysalary <= 0)){
         $('#sendofferdialog #saveerror').html('试用期月薪必须为正整数！').fadeIn().fadeOut(5000);
         return false;
      }

      from = $.map(from.split('-'), function(n) {
    	  return padDate(parseInt(n));
      }).join('-');
      
      if(entryenddate != '' && entryenddate <= from){
         $('#sendofferdialog #saveerror').html('试用期结束时间必须大于开始时间！').fadeIn().fadeOut(5000);
         return false;
      }
      if(copywith != ''){
         var arremail=copywith.replace(/\s+/g, "");
             arremail=arremail.split(",");
         for(var i=0;i <arremail.length;i++){
            if(arremail[i].length>0){
               if(!validateEmail(arremail[i])){
                  $('#sendofferdialog #saveerror').html('不合法的邮箱:'+arremail[i]).fadeIn().fadeOut(5000);
                  return false;
               }
            }
         }
      }

      var html = '<form id="previewofferform">';
      html += '<div class="modal-header">';
      html += '<h3>'+icomp_name+'</h3>';
      html += '</div>';
      html += '<div class="modal-body">';
      html += '<div class="bs-content">';
      html += '<div style="padding:0 8px;">';
      html += '<p class="p_title"><b>聘用通知书</b></p>';
      html += '</div>';
      html += '<div style="padding:15px 25px 0 25px;">';
      html += '<p class="p_text">亲爱的 <b style="color:#ff6600;">'+jobseekername+'</b>，您好！</p>';
      html += '<p class="p_text t_intent">很高兴通知您通过了面试，我公司荣幸地聘请您为：<b>'+jobtitle+'</b>。我们相信您的技能和资历将为公司带来很大价值，衷心期待您的加盟。</p>';
      html += '<p class="p_text t_intent">有关职位具体信息如下，在您正式入职时生效：</p>';
      html += '</div>';
      html += '<div class="bs_content_bgimg">';
      html += '<p class="p_text t_intent">职位：'+jobtitle+'</p>';
      html += '<p class="p_text t_intent">入职时间：'+from+' '+fromtime+'</p>';
      html += ((entryenddate == '')?'':'<p class="p_text t_intent">试用期至：'+entryenddate+'</p>');
      html += ((department == '')?'':'<p class="p_text t_intent">部门：'+department+'</p>');
      html += ((entrysalary == '')?'':'<p class="p_text t_intent">试用期月薪：'+entrysalary+'元</p>');
      html += ((salary == '')?'':'<p class="p_text t_intent">转正月薪：'+salary+'元</p>');
      html += '<p class="p_text t_intent">'+textval+'</p>';
      html += '</div>';
      html += '<input name="accessclass" value="PUBLIC" type="hidden">';
      html += '<input name="jobtitle" value="'+jobtitle+'" type="hidden">';
      html += '<input name="textval" value="'+textval+'" type="hidden" id="textval">';
      html += '<input name="entrysalary" value="'+entrysalary+'" type="hidden" id="entrysalary">';
      html += '<input name="salary" value="'+salary+'" type="hidden" id="salary">';
      html += '<input name="fromtime" value="'+fromtime+'" type="hidden" id="fromtime">';
      html += '<input name="from" value="'+from+'" type="hidden" id="from">';
      html += '<input name="jobseekerid" value="'+jobseekerid+'" type="hidden" id="jobseekerid">';
      html += '<input name="jobid" value="'+jobid+'" type="hidden" id="jobid">';
      html += '<input name="department" value="'+department+'" type="hidden" id="department">';
      html += '<input name="jobseekername" value="'+jobseekername+'" type="hidden" id="jobseekername">';
      html += '<input name="calendar" value="'+calendar+'" type="hidden" id="calendar">';
      html += '<input name="attachmentid" value="'+attachmentid+'" type="hidden" id="attachmentid">';
      html += '<input type="hidden" name="copywith" value="'+copywith+'" id="copywith">';
      html += '<input name="filename" value="'+filename+'" type="hidden" id="filename">';
      html += '<input name="entryenddate" value="'+entryenddate+'" type="hidden" id="entryenddate">';
      html += '<input name="type" value="'+type+'" type="hidden" id="type">';
      html += '<input name="objectid" value="'+objectid+'" type="hidden" id="objectid">';
      html += '<input name="summary" value="入职" type="hidden" id="summary">';
      html += '<input name="objecttype" value="VTODO" type="hidden" id="objecttype">';
      html += '<input name="eventtype" value="'+eventtype+'" type="hidden" id="eventtype">';
      html += '<input name="id" value="'+eventid+'" type="hidden" id="id">';
      html += '<input name="sendsms" value="'+sendsms+'" type="hidden" id="sendsms">';
      html += '<div class="bs_content_butn">';
      html += '<span id="sendofferror" class="error" style="display:none;">保存失败</span>';
      html += '<span id="sendoffsuccess" class="success" style="display:none;">发送成功</span>';
      html += '<button type="button" class="ppp_bluebtn btn-sure" id="sendofferbutton">确认发送</button><a id="backedit" href="javascript:;" style="margin-left:15px;">修改</a>';
      html += '</div>';
      html += '</div>';
      html += '</div>';
      html += '</form>';
      if(type == 0){
         $("#interviewsuccess").html(html);
         showLoading('#previewoffertpl', null, null, {button: true});
         $("#sendofferdialog").modal('hide');
         $('#sendofferbutton').trigger("click");
      }else{
         $("#sendofferdialog").modal('hide');
         var scrolltop = $(window).scrollTop();
         $("#interviewsuccess").html(html).css({top:scrolltop+75}).modal();
      }
   });

   //Send out offer dialog
   $(document).on('click', '#sendofferbutton', function() {
      var target = $(this);
      var eventtype = $("input[name=eventtype]").val();
      var url = '';
      var type = $("#sendofferdialog #marker").val();
      var sendmsg = (type == 0) ? "简历状态成功改为已发offer！" : "聘用通知书发送成功！";
      if(eventtype == 'addoffer'){
         url = sendoffer;
      }else{
         url = OC.filePath('calendar', 'ajax/event', 'edit.offer.php');
      }
      $.ajax({
         type: "POST",
         url: url,
         data: $( "#previewofferform" ).serialize(),
         dataType: 'json',
         beforeSend: function(xhr, settings) {
            showLoading(target, settings, null, {button: true});
         },
         success: function(data) {
            try {
               var retmsg = data;
               if (retmsg.error) {
                  $("#sendofferror").jobUtil('showError', retmsg.error);
               }
               else if(retmsg.success) {
                  $('#sendofferdialog').hide();
                  $('#interviewsuccess').fadeOut(1000,function(){
                     showStatusDialog(sendmsg,function(){
                        window.location.reload();
                     });
                  }).modal('hide'); 
               }
            } catch(e) {
               return false;
            }
         }
      });
   });

   $(document).on('click','#cancel',function(){
      $('#sendofferdialog .close').trigger('click');
   });

   //Entryend datepicker js
   $(document).on('focus','#entryend',function(){
      $(this).datepicker({
         dateFormat: 'yy-mm-dd',
         changeYear: true,
         changeMonth: true,
         numberOfMonths: 1,
         minDate: new Date(),
         onClose: function(dateText) {
            if(dateText != $(this).attr("title"))
               $(this).removeClass("blur");
            else
               $(this).blur();
         }
      });
   });

   //Attachment apply js
   $(document).on('click','#attachment #attachment_list .apply',function(){
      var target = $(this);
      var attachmentid = target.attr('id');
      var jobid = $('#notify_form #jobid').val();
      var file_name = $(this).text();
      $("#uploadoffererror").html("");
      $.ajax({
          type: "GET",
          url: OC.filePath('calendar', 'ajax/tpl', 'get.attachment.php'),
          data: {attachmentid: attachmentid,jobid: jobid},
          dataType: 'json',
          beforeSend: function(xhr, settings) {
             showLoading(target, settings, null, {button: true});
          },
          success: function(data){
             try {
                var retmsg = data;
                if (retmsg.error) {
                   showMessagePanel(retmsg.error, target, true, {placement:'left'});
                }
                else if(retmsg.success) {
                	$('#attachment #filename').remove();
                    $('#notify_form #attachment').prepend('<input id="filename" type="text" name="" placeholder="" value="'+file_name+'" attachmentid="'+attachmentid+'" readonly="readonly" style="width:258px;">');
                }
             } catch(e) {
                return false;
             }
          }
       });
      return false;
   })

   // Delete attachment js
   $(document).on('click','#attachment #attachment_list .delete', function() {
      var target = $(this).parent();
      var attachmentid = target.attr('id');
      var jobid = $('#notify_form #jobid').val();
      var file_name = $(this).prev("span").html();
      $.ajax({
         type: "POST",
         url: OC.filePath('calendar', 'ajax/tpl', 'del.attachment.php'),
         data: {attachmentid: attachmentid,jobid: jobid},
         dataType: 'json',
         beforeSend: function(xhr, settings) {
            showLoading(target, settings, null, {button: true});
         },
         success: function(data){
            var retmsg = data;
            if (retmsg.error) {
               showMessagePanel(retmsg.error, target, true, {placement:'left'});
            }
            else if(retmsg.success) {
               $('#attachment #attachment_list #'+attachmentid).remove();
               if( $('#notify_form #attachment_list .apply').children().length==0 ) {
                  $('#notify_form .inviteselectmenubox').removeClass('dropdown open');
                  $('#notify_form #invs_one').removeClass('dropdown open');
                  $('#notify_form #choose_tpl').attr('data-toggle','');
               }
               var now_file_name = $("#sendofferdialog #filename").val();
               if(now_file_name == file_name) {
                  $("#sendofferdialog #filename").val("");
               }
            }
         }
      });
      return false;
   });

   //Marker js
   $(document).on('click','#marker',function(){
      var key = $(this).val();
      if(key == 1){
         $("#previewoffertpl").text('确认');
         $(this).val(0);
         $('.sendsety_cbg').hide();
         $("#sendofferdialog #previewoffertpl").removeClass("ppp_graybtn").addClass("ppp_bluebtn").css("cursor","pointer");
      }else{
         $("#previewoffertpl").text('预览');
         $(this).val(1);
         $('.sendsety_cbg').show();
         if($('#sendofferdialog #sendemail').is(':checked')) {
            $("#sendofferdialog #previewoffertpl").removeClass("ppp_graybtn").addClass("ppp_bluebtn").css("cursor","pointer");
         } else {
            if($("#sendofferdialog #sendsms").is(':checked')){
               $("#sendofferdialog #previewoffertpl").removeClass("ppp_graybtn").addClass("ppp_bluebtn").css("cursor","pointer");
            }else{
               $("#sendofferdialog #previewoffertpl").removeClass("ppp_bluebtn").addClass("ppp_graybtn").css("cursor","default");
            }      
         }
      }
   });

   //Copywith js
   $(document).on('click','.controls .recentselected',function(){
      if($.trim($("#carboncopy #copywith").val()).length <= 0)
         $("#carboncopy #copywith").val($(this).text());
      else
         $("#carboncopy #copywith").val($("#carboncopy #copywith").val()+','+$(this).text());
   })

   $(document).bind('keydown', function(event) {
      if(event.keyCode == 27) {
         $(".popup").not('.keepopen').hide();
         return true;
      }
   });

   $(document).bind('mousedown', function(e){
      e = $.event.fix(e);
      var otarget = $(e.target);
      if(otarget.closest(".popup").length>0) {
         if(otarget.hasClass("close")) {
            otarget.closest(".popup").hide();
            return true;
         }
         return true;
      }

      // close all popup 
      $(".popup").not('.keepopen').hide();
      return true;
   });

   $(document).on('click','#cancelEvent', function() {
      var target = $(this);
      $.metadata.setType('attr', 'data');
      var data = $(this).metadata()
      var eventid = data.eventid;
      var jobid = data.jobid;
      var eventtype = $(this).attr('eventtype');
      var jobseekerid = data.jobseekid;
      if(eventtype == 'VTODO'){
         var type = '确认取消该入职么?';
      }else{
         var type = '<div class="ciw_words"><i></i> 取消面试将会发送通知给面试官和应聘者，您确认要取消面试吗？</div>';
      }
      showConfirmDialog(type,function() {
         $.ajax({
            type: "POST",
            url: cancelevent,
            data: {eventid: eventid,jobid: jobid,eventtype: eventtype,jobseekerid: jobseekerid},
            dataType: 'json',
            beforeSend: function(xhr, settings) {
               showLoading(target, settings, null, {button: true});
            },
            success: function(data){
               try {
                  var retmsg = data;
                  if (retmsg.error) {
                     showMessagePanel(retmsg.error, target, true, {placement:'right'});
                  }
                  else if(retmsg.success) {
                     window.location.reload();
                  }
               } catch(e) {
                  return false;
               }
            }
         });
      });
      return false;
   });
   
   $(document).on('click','#choosehistory',function(){
      var target = $(this);
      $.metadata.setType('attr', 'data');
      var data = $(this).metadata();
      var attachid = data.attachid;
      var attachname = data.attachname;
      $("#fileshowarea").show().html("<span class='"+attachid+"' <em>"+attachname+"</em> <a href='javascript:;' id='del_name'  data={'attachid':'"+attachid+"'}>取消</a></br></span>");
      $("#attachment").val(attachid);
   });
   
   $(document).on('click','#del_name,#history_atachment',function(){
     var target = $(this);
     $.metadata.setType('attr', 'data');
     var data = $(this).metadata();
     var attachid = data.attachid;
     var jobid = $('#jobid').val();
     var attachname = ''
     if(data.hasOwnProperty('attachname') && $(this).attr("id") == "history_atachment")
        attachname = data.attachname;
     $.ajax({
        type: "POST",
        url: OC.filePath('calendar', 'ajax/tpl', 'del.attachment.php'),
        data: {attachmentid:attachid,attachname:attachname,jobid:jobid,type:'interview'},
        dataType: 'json',
     
        success: function(retmsg){
           if(retmsg.success){
              $('.'+retmsg.success).remove();
              if(attachname != ''){
                 $('.this'+attachid).remove();
                 if($('.history_list').find('a').length == 0){
                    $('#calendar_att_div .inviteselectmenubox').removeClass("dropdown open");
                    $('#calendar_att_div .inviteselectmenubox #invs_two').attr('data-toggle','');
                 }
              }
              if(jQuery.trim($('#fileshowarea').html()) == ''){
                 $('#fileshowarea').hide();
                 $('#attachment').val('');
                 $(".errors").fadeOut(3000);
              }
           }else if (retmsg.error) {
              $(".errors").show().html(' <div class="error">' + retmsg.error +'</div>');;
              $(".errors").fadeOut(3000);
           }
        }
     });
     return false;
   });

   $(".caln_setinvite a").click(function(){
      $("#searchinterview_dialog").modal();
   });

   /* Add A New Calendar event */
   var showAddEventModal = function(data) {
      var target = data.target;
      var jobseekerid = data.jobseekerid;
      var jobseekername = data.jobseekername;
      var jobid = data.jobid;
      var jobtitle = data.jobtitle;
      var source = data.source;
      var objectid = data.objectid;
      var round = data.round;
      var type = data.type;
      var validemail = data.validemail;

      $.ajax({
         url: OC.filePath('calendar', 'ajax/event', 'new.form.php'), 
         data: {jobseekerid:jobseekerid, jobseekername:jobseekername, jobid:jobid, jobtitle:jobtitle,objectid:objectid, round:round,type:type,validemail:validemail,source:source}, 
         dataType: 'html', 
         beforeSend: function(xhr, settings) {
            showLoading(target, settings, null, {button:true});
         },
         cache: false,
         success: function(html){
            $('#event_modal').html(html);
            $('label.checkbox.gray').tooltip();
            setTimeout(function () {
               if(!$('#event_modal #sendemail').is(':checked')) {
                  if(!$('#event_modal #sendsms').is(':checked') && $('#event_modal #sendsms').attr("disabled") != "disabled") {
                     showMessagePanel('简历缺少Email信息，请设置发送短信', $("#event_modal #sendsms").parent("label"), true, {placement:'right', timeout:3000});
                  }
               }
            }, 500);
            if($.isFunction($.fn.placeholder)) {
               $("input, textarea", "#event_modal").placeholder();
            }
            $("#event_modal #event_form").validate({
               rules: {
                  contact_phone: {required:true,phone: true},
                  address: {required: true},
                  contact: {notalldigits:true}
               },
               messages: {
                  contact_phone: {
                     required: "请输入联系电话",
                     phone: "请输入正确的联系电话"
                  },
                  address: {
                     required: "请输入面试地点"
                  },
                  contact: {
                     notalldigits:"联系人不能为纯数字"
                  }
               },
               success:function(label){
                  var prev = $("#event_modal #errorbox").data("element");
                  if ( label.attr("for") == prev && (prev == "contact_phone" || prev == "address" || prev == "contact") ) {
                     $("#event_modal #errorbox").data("element", "").html("").hide();
                  }
               },
               errorPlacement:function(error,element) {
                  var validator = $("#event_modal #event_form").data("validator");
                  if ( element.attr("name") == "during[]" ) {
                     error.insertAfter("#event_form #addinterviewer");
                  } else if ( element.attr("name") == "contact_phone" || element.attr("name") == "address" || element.attr("name") == "contact" ) {
                     var prev = $("#event_modal #errorbox").data("element");
                     if(prev) {
                        if($.grep(validator.errorList, function(error, i) {      
                           if($(error.element).attr("name") == prev) 
                              return true;
                           return false;
                        }).length > 0)
                           return;
                     }
                     if(error.text()) {
                        $("#event_modal #errorbox").data("element", element.attr("name")).jobUtil('showError', error.text());
                     }
                  } else {
                     error.insertAfter(element);
                  }
               },
               submitHandler: function(form) {
                  if($("#event_modal #event_form #submitNewEvent").hasClass("ppp_graybtn")) {
                     return false;
                  }
                  $("#event_modal #event_form").ajaxSubmit({
                     type: 'post',
                     dataType: "json",
                        beforeSubmit: function(data, form, options) {
                           if (!showLoading("#event_modal #submitNewEvent", options, null, {button:true}))
                              return false;
                           $("#event_modal #errorbox").hide();
                        },
                        success: function(data) {
                           try {
                              var retmsg = data;
                              if (retmsg.error) {
                                 $("#event_modal #errorbox").jobUtil('showError', retmsg.error);
                              }
                              else if(retmsg.success) {
                                 $('#event_modal').modal('hide');
                                 $('#searchinterview_dialog').modal('hide');
                                 if (type == 1) {
                                    $('#getresult_dialog').modal();
                                    $('#getresult_dialog').on('hidden',function(){
                                       window.location.reload();
                                    });
                                 } else {
                                    var scrolltop = $(window).scrollTop();
                                    $("#notify_showdialog").css({top:scrolltop+100}).modal();
                                    $('#notify_showdialog').on('hidden',function(){
                                       window.location.reload();
                                    });
                                 }
                              }
                           } catch(e) {
                              return false;
                           }
                        }
                  });
               }
            });
            $("#event_modal").modal("show");
            //upload interview attachment  
            jQuery('#uploadcalendarform').not('.file_upload').fileUploadUIX({
               allowOfficeTypes: true,
               keepList: true,
               autoUpload: true,
               maxFileSize: 4*1024*1024,
               onError:function(response){
                  $("#uploadcalendartable tr:last").remove();
                  $(".errors").show().html(' <div class="error">' + response +'</div>');;
                  $(".errors").fadeOut(3000);
                  return false;
               },
               onCompleteAll: function(list) {
                  jQuery.each(list, function(i, o) {
                     var handler = o.slice(-1)[0];
                     if(handler.response.error) {
                        $(".errors").show().html(' <div class="error">' + handler.response.error +'</div>');
                        $(".errors").fadeOut(3000);
                     }else{
                        $("#fileshowarea").show().html("<span class="+handler.response.attachid+" fileshoweach <em>"+handler.response.name+"</em> <a href='javascript:;' id='del_name' data = {'attachid':'"+handler.response.attachid+"','attachname':'"+handler.response.name+"'}>取消</a></br></span>");
                        $("#attachment").val(handler.response.attachid);
                        $(".errors").show().html(' <div class="success">成功上传</div>');
                        if(!$('#calendar_att_div .inviteselectmenubox').hasClass("dropdown")){
                           $('#calendar_att_div .inviteselectmenubox').addClass("dropdown");
                           $('#calendar_att_div .inviteselectmenubox .dropdown-toggle').dropdown();
                        }
                        $(".history_list").append("<a  id='choosehistory' data={'attachname':'"+handler.response.name+"','attachid':'"+handler.response.attachid+"'} href='javascript:;' class='this"+handler.response.attachid+"'> <span  style='display:inline;'>"+handler.response.name+"</span><i data={'attachid':'"+handler.response.attachid+"','attachname':'"+handler.response.name+"'} id='history_atachment' class='delete'></i></a>");
                        $(".errors").fadeOut(3000);
                        $("#uploadcalendartable tr:last").remove();
                     }    
                  });
               }
           });
         }
      });
   };

   var checkJobSelect = function(data) {
      var target = $(this);
      $(this).jobSelect({
         title: '选择职位',
         listurl: alljoblist_url,
         selected:function(){
            var fContainer = $(this);
            var jobObj = $('.itemlist a.selectjob.cur_a', fContainer);
            var confirmBtn = $('.selectjobconfirm', fContainer);
            if(jobObj.length > 0){
               $.ajax({
                  type: "POST",
                  url: OC.filePath('resumes', 'ajax', 'savejob.php'),
                  data: {jobid: jobObj.data('jobid'), jobseekerid: data.jobseekerid},
                  beforeSend: function(xhr, settings) {
                     if(!showLoading(confirmBtn, settings, null, {button:true}))
                        return false;
                     $('.server', fContainer).hide();
                  },
                  success: function(result){
                     if (!isLoggedIn(result, jQuery("#floatcontainer"))) {
                        window.location = redirect_url;
                        return;
                     }

                     if(!$.isPlainObject(result)) {
                        result = $.parseJSON(result);
                     }

                     if(result.status === 'success') {
                        data.jobid = jobObj.data('jobid');
                        data.jobtitle = jobObj.data('jobtitle');
                        data.jobsystem = 0;
                        target.data('eventdata', data);
                        /*刷新之前选择的简历的申请职位*/
                        var url = getUrlQuery(jobsetupurl, "id=" + data.jobid + "&job_title=" + data.jobtitle);
                        $(".selected_trline").children().eq(3).addClass('editByJobid').data('jobid', jobObj.data('jobid')).html('<a href="'+url+'">'+data.jobtitle+'</a>');
                        
                        fContainer.modal('hide');
                        showAddEventModal(data);
                     } else {
                        showMessagePanel(result.data.message, confirmBtn, true, {placement:'right'});
                     }
                  }
               });
            } else {
               $('.server', fContainer).text('请选择职位').show();
            }
         },
         emptySelected:function(){
            $('.itemlist a.cur_a', $(this)).removeClass('cur_a');
         },
         cancelSelected:function(){
            $("#floatcontainer").modal('hide');   
            $('#searchinterview_dialog').modal();
         }
      });
   }
   $("#addevent").click( function() {
      var target = $(this);
      $.metadata.setType("attr", "data");
      var data = typeof(target.data('eventdata'))=='undefined' ? $.extend({}, target.metadata()) : target.data('eventdata');
      data.target = target;
      //type 0: not from search
      data.type = 0;

      if(data.jobsystem==1) {
         checkJobSelect(data);
      } else {
         showAddEventModal(data);
      }

      return false;
   });

   $(document).on('click','#caln_setinvite',function(){
      var target = $(this);
      $.ajax({
         type: "POST",
         url: OC.filePath('calendar', 'ajax/event', 'search.interview.php'),
         dataType: 'html',
         beforeSend: function(xhr, settings) {
            showLoading(target, settings, null, {button: true});
            $("#searchinterview_dialog").empty();
         },
         success: function(result){
            $("#searchinterview_dialog").html(result).modal();
            if($.isFunction($.fn.placeholder)) {
               $("#search_keyword").placeholder();
            }
         }
      });
   });

   $(document).on('click','#interview_resume_search',function(){
      var target = $(this);
      var keyword = $.trim($('#search_keyword').focus().val());
      var type = 1;
      $.ajax({
         type: "POST",
         url: OC.filePath('resumes', 'ajax', 'search.resume.php'),
         data: {keyword:keyword,type:type},
         dataType: 'html',
         beforeSend: function(xhr, settings) {
            showLoading(target, settings, null, {button: true});
         },
         success: function(result){
            $("#search_resume_resut").html(result);
         }
      });
   });

   $(document).on('keydown','#search_keyword',function(e){
      if(e.which == 13) {
         e.preventDefault();
         $('#interview_resume_search').trigger('click');
      }
   });

   $(document).on('click','#searchinterview_dialog .btn-info',function(){
      var target2 = $(this);
      var val=$('input:radio[name="chooseresume"]:checked').val();
      if(!val){
         target = $(this);
         showMessagePanel('请先选择一份简历！', target, true, {placement:'right'});
         return false;
      }
      else{
         var target = $('#chooseresume_'+val);
         $.metadata.setType('attr', 'data');
         var data = target.metadata();
         data.target = target;
         var jobseekerid = data.jobseekerid;
         $.ajax({
            type: "POST",
            url: OC.filePath('calendar', 'ajax', 'getinterviewresult.php'),
            data: {jobseekerid:jobseekerid},
            dataType: 'json',
            beforeSend: function(xhr, settings) {
               showLoading(target2, settings, null, {button: true});
            },
            success: function(result){
               var retmsg = result;
               if(retmsg.success) {
                  data.round = retmsg.success.round;
                  data.eventid = retmsg.success.objectid;
                  //type 1: from search 
                  data.type = 1;
                  //interview_stat 1:update 2:new 3:entry 4: offer 5:reset
                  if(retmsg.success.interview_stat == 2){
                     $('#searchinterview_dialog').modal('hide');
                     if(data.jobsystem==1) {
                        checkJobSelect(data);
                     } else {
                        showAddEventModal(data);
                     }
                  }else if(retmsg.success.interview_stat == 1){
                     $('#searchinterview_dialog').modal('hide');
                     editInterview(data);
                  }else if(retmsg.success.interview_stat == 5){
                     $('#searchinterview_dialog').modal('hide');
                     data.resultid = 5;
                     editInterview(data);
                  }else if(retmsg.success.interview_stat == 4){
                     target = data.target;
                     showMessagePanel('该简历已经发过offer，不能再安排面试！', target, true, {placement:'right'});
                  }else if(retmsg.success.interview_stat == 3){
                     target = data.target;
                     showMessagePanel('该简历已经进入入职流程，不能再安排面试！', target, true, {placement:'right'});
                  }
               }
            }
         });
      }
   });

   $(document).on('click','.haveserresult_table table tr:gt(0)',function(){
      $(this).siblings().removeClass("selected_trline");
      $(this).addClass("selected_trline"); 
      $(this).find("input").attr("checked","checked");
   });

   if(/adddialog=(.*)/.test(window.location.search)) {
        
      if(window.location.hash == "#show")
         return;
      $('#caln_setinvite').trigger('click');
      window.location.hash = "#show";
   }else{
      if($('#neverset_dialog').length > 0) {
      $('#neverset_dialog').modal();
      $('#neverset_dialog').on('click','.nvs_setbtn a',function(){
      $('#neverset_dialog').modal('hide');
      $('#caln_setinvite').trigger('click');
      })
   }
   }

   $(document).on('click','#previous_step',function(){
      $('#event_modal').modal('hide');
      $('#modal_holder').modal('hide');
      $('#searchinterview_dialog').modal();
   })

   //安排面试:如果短信和email都没有被勾选,按钮则为不能点击状态
   $(document).on('click', '#event_modal #sendsms', function(){
      if($('#event_modal #sendemail').is(':checked')) {
         if($(this).is(':checked'))
            $(this).val('sms');
         else
            $(this).val('');
         $("#event_modal #submitNewEvent").removeClass("ppp_graybtn").addClass("ppp_bluebtn").css("cursor","pointer");
      } else {
         if($(this).is(':checked')){
            $(this).val('sms');
            $("#event_modal #submitNewEvent").removeClass("ppp_graybtn").addClass("ppp_bluebtn").css("cursor","pointer");
         }else{
            $(this).val('');
            $("#event_modal #submitNewEvent").removeClass("ppp_bluebtn").addClass("ppp_graybtn").css("cursor","default");
         }        
      }
   });

   //修改面试:如果短信和email都没有被勾选,按钮则为不能点击状态
   $(document).on('click', '#modal_holder #sendsms', function(){
      if($('#modal_holder #sendemail').is(':checked')) {
         if($(this).is(':checked'))
            $(this).val('sms');
         else
            $(this).val('');
         $("#modal_holder #editEvent-submit").removeClass("ppp_graybtn").addClass("ppp_bluebtn").css("cursor","pointer");
      } else {
         if($(this).is(':checked')){
            $(this).val('sms');
            $("#modal_holder #editEvent-submit").removeClass("ppp_graybtn").addClass("ppp_bluebtn").css("cursor","pointer");
         }else{
            $(this).val('');
            $("#modal_holder #editEvent-submit").removeClass("ppp_bluebtn").addClass("ppp_graybtn").css("cursor","default");
         }        
      }
   });
   
   //发送offer:如果短信和email都没有被勾选,按钮则为不能点击状态
   $(document).on('click', '#sendofferdialog #sendsms', function(){
      if($('#sendofferdialog #sendemail').is(':checked')) {
         if($(this).is(':checked'))
            $(this).val('sms');
         else
            $(this).val('');
         $("#sendofferdialog #previewoffertpl").removeClass("ppp_graybtn").addClass("ppp_bluebtn").css("cursor","pointer");
      } else {
         if($(this).is(':checked')){
            $(this).val('sms');
            $("#sendofferdialog #previewoffertpl").removeClass("ppp_graybtn").addClass("ppp_bluebtn").css("cursor","pointer");
         }else{
            $(this).val('');
            $("#sendofferdialog #previewoffertpl").removeClass("ppp_bluebtn").addClass("ppp_graybtn").css("cursor","default");
         }      
      }
   });
});
